import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

import {
  separateHandle
} from '@/utils/testEnv'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/jump'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // separateHandle(to)
  console.log(to, from, 'new Date().getTime()')
  store.commit("permission/SET_TIMESTAMP", new Date().getTime());
  store.commit("permission/SET_FROMROUTE", from.name);
  store.commit("permission/SET_TOROUTE", to.name);
  let pID = to.query.applicationId;
  //超时退出后，刷新到商机登录页问题

  let applicationId = ''

  if (!from.query.applicationId) {
    applicationId = to.query.applicationId
    //  to.query.applicationId = from.query.applicationId
  } else {
    applicationId = from.query.applicationId
  }
  //无参数 默认为1
  // if (!applicationId) applicationId = 'all'
  if (!applicationId) applicationId = 'all';

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title, to.meta.zhTitle)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path == '/contract-login') {
      next({
        // path: '/contract-login',
        path: '/login',
        applicationId: '454556140475292421'
      })
    }
    if (store.getters.isLock && to.path !== '/lockScreen' && to.path !== '/login') {
      next({
        path: '/lockScreen',
        query: {
          applicationId: applicationId
        }
      })
      NProgress.done()
    } else if (to.path === '/login' || to.path === '/') {
      // if is logged in, redirect to the home page
      next({
        path: '/dashboard',
        query: {
          applicationId: ''
        }
      })
      NProgress.done()
    } else {
      const hasMenu = store.getters.menuList && store.getters.menuList.length > 0
      if (hasMenu) {
        if (to.query.applicationId) {
          // 对 dashboard 参数 特殊处理一下
          if (to.path == '/dashboard' && to.query.applicationId != applicationId) {
            to.query.applicationId = applicationId
            next({
              ...to
            })
          } else {
            next()
          }
        } else {
          to.query.applicationId = applicationId
          next({
            ...to
          })
        }
      } else {
        try {
          // get user info
          let res = await store.dispatch('user/getInfo')
          const accessRoutes = await store.dispatch('permission/generateRoutes', res)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          if (error && typeof (error) == 'string') Message.error(error || 'Has Error')
          // 超出登录，判断applicationId 和是否合同登录页
          if (pID == '454556140475292421' && to.path != 'contract-login') {
            // next(`/contract-login?redirect=${to.path}`)
            next(`/login?redirect=${to.path}`)
          } else {
            next(`/login?redirect=${to.path}`)
          }
          NProgress.done()
        }
      }
    }
  } else {
    if (to.path == '/contract-login') {
      next({
        // path: '/contract-login',
        path: '/login',
        applicationId: '454556140475292421'
      })
    }
    if (pID == '454556140475292421' && to.path != '/contract-login') {
      next({
        // path: '/contract-login',
        path: '/login',
        applicationId: '454556140475292421'
      })
    }
    /* has no token*/
    // 多层判断
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.path == '/login') {
        next({
          applicationId: 'all'
        })
      } else {
        if (to.query.applicationId) {
          next()
        } else {
          to.query.applicationId = applicationId
          next({
            ...to
          })
        }
      }
    } else {
      // other pages that do not have permissionEle to access are redirected to the login page.
      if (to.path == '/contract-login') {
        to.query.applicationId = '454556140475292421'
        next({
          'applicationId': to.query.applicationId
        })
        return;
      }
      if (to.path == '/login') {
        to.query.applicationId = 'all'
        next({
          'applicationId': to.query.applicationId
        })
        return;
      }

      // next(`/login?redirect=${to.path}`)
      // console.log('to.path111111111', to)
      // 如果上述无，判断合同applicationId 如果存在跳转合同login，如果不存在跳转login商机
      if (to.query.applicationId == '454556140475292421') {
        // next(`/contract-login?applicationId=454556140475292421`)
        next(`/login?applicationId=454556140475292421`)
      } else {
        next(`/login?redirect=${to.path}applicationId=all`)
      }
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
